<?php

namespace app\api\controller\orderreceipt;

use app\api\controller\Base;
use app\api\controller\mytool\Sendmessage;
use app\api\controller\Pub;
use app\api\controller\sync\Synccreate;
use app\common\model\orderdata\Goods;
use app\common\model\orderdata\StorageAreaGoods;
use app\common\model\orderhawa\Hawa;
use app\common\model\orderhawa\HawaList;
use app\common\model\orderreceipt\Receipt;
use app\common\model\orderreceipt\ReceiptList;
use app\common\model\power\Rolepower;
use app\common\model\user\User as UserModel;

class Orderreceiptbuss extends Base
{
    /**
     * 产生jwt加密串，参考session
     */
    public function initialize()
    {
        parent::initialize();
        self::is_login();
        Rolepower::powerguard(201006);
    }

    /**
     * 获取订单列表
     * @return [type] [description]
     */
    function list() {
        $data = input('get.');
        //使用type 确定排序的关键词
        $data['Type'] = 'ware';
        $data         = init_where($data);
        $list         = ReceiptList::usergetlist($data, 'buss');

        $list['tr']['title'] = ['订单号', '登记时间', '订单状态', '查看'];
        $list['tr']['key']   = ['OrderNumber', 'WarehouseTime', 'State', 'ReceiptListId'];
        return myok($list);
    }

    /**
     * 获取订单信息
     * @return [type] [description]
     */
    public function getinfo()
    {
        $id = input('id');
        if (empty($id)) {
            return myerr('缺少参数，请重新尝试');
        }
        $data = ReceiptList::getinfo($id, 'buss');
        if (!$data['code']) {
            return myerr($data['msg']);
        }
        $data = $data['msg'];
        if (empty($data['hawalist'])) {
            $ordata           = ['where' => [['State', HawaList::STATETRANSPORT], ['ReceiptListId', $id]], 'Type' => 'orderhawabuss'];
            $data['hawalist'] = HawaList::usergetlist($ordata, 'buss', false);
        }
        $data['FLOATINGWEIGHT'] = FLOATINGWEIGHT;
        $data['CELLPHONE']      = CELLPHONE;
        return myok($data);
    }

    /**
     * 确认入库
     * @return [type] [description]
     */
    public function confirmorder()
    {
        $data                = input('post.');
        $data['HawaListIds'] = explode(',', $data['HawaListIds']);

        //检测入库重量与订单重量是否满足浮差
        if (FLOATINGWEIGHT !== -1) {
            $goodlist        = [];
            $checkedgoodlist = [];
            $ordata          = ['where' => [['State', HawaList::STATETRANSPORT]], 'Type' => 'orderhawabuss'];
            $hawalist        = HawaList::usergetlist($ordata, 'buss', false);
            foreach ($hawalist['list'] as $key => $value) {
                foreach ($value['listinfo'] as $key2 => $value2) {
                    if (empty($goodlist[$value2['GoodId']])) {
                        $goodlist[$value2['GoodId']] = $value2['Weight'];
                    } else {
                        $goodlist[$value2['GoodId']] = $goodlist[$value2['GoodId']] + $value2['Weight'];
                    }
                }
            }

            $ordata   = ['where' => [['State', HawaList::STATETRANSPORT], ['HawaListId', 'in', $data['HawaListIds']]], 'Type' => 'orderhawabuss'];
            $hawalist = HawaList::usergetlist($ordata, 'buss', false);
            foreach ($hawalist['list'] as $key => $value) {
                foreach ($value['listinfo'] as $key2 => $value2) {
                    if (empty($checkedgoodlist[$value2['GoodId']])) {
                        $checkedgoodlist[$value2['GoodId']] = $value2['Weight'];
                    } else {
                        $checkedgoodlist[$value2['GoodId']] = $checkedgoodlist[$value2['GoodId']] + $value2['Weight'];
                    }
                }
            }

            foreach ($checkedgoodlist as $key => $value) {
                if (!empty($goodlist[$key])) {
                    if (($value * FLOATINGWEIGHT / 100) < $goodlist[$key] - $value) {
                        $goodinfo = Goods::get($key);
                        return myerr('【' . $goodinfo->OrderNumber . '】收集重量与入库重量差距过大');
                    }
                }
            }
        }
        //检测订单状态是否允许入库
        $sb = ReceiptList::get($data['id']);
        if (empty($sb)) {
            return myerr('没有找到此入库订单');
        }

        if ($sb->State !== ReceiptList::STATEWAIT) {
            return myerr('订单状态错误，无法确认');
        }

        if ($sb->BussinessId !== Pub::userid()) {
            return myerr('没有权限修改订单');
        }

        //产废订单表标记为货物入库
        $sb = HawaList::receipt($data);
        if (!$sb['code']) {
            return myerr('收集单入库失败');
        }

        //修改入库订单同时修改产品重量
        $sb = ReceiptList::receipt($data);
        if (!$sb['code']) {
            return myerr('入库主订单修改失败');
        }

        //修改货物表的库存
        $goodlist = Receipt::where('ReceiptListId', $data['id'])->field('GoodId,Weight')->select();
        $goodids  = get_array_id($goodlist, 'GoodId','','',false);
        $weights  = get_array_id($goodlist, 'Weight','','',false);
        Goods::weight_change($goodids, $weights);

        //修改库存货物区域表的库存
        foreach ($data['HawaListIds'] as $v) {
            $hawa_list = Hawa::where('HawaListId', $v)->select();
            if (empty($hawa_list)) {
                continue;
            }
            foreach ($hawa_list as $key => $value) {
            	$s_a_g_info = StorageAreaGoods::where([
	                'GoodId'        => $value->GoodId,
	                'StorageAreaId' => $value->StorageAreaId,
	                'GoodName'      => $value->GoodName,
	            ])->findOrEmpty();
	            //更改库存区域重量
	            if ($s_a_g_info->isEmpty()) {
	                StorageAreaGoods::create([
	                    'GoodId'        => $value->GoodId,
	                    'StorageAreaId' => $value->StorageAreaId,
	                    'GoodName'      => $value->GoodName,
	                    'Weight'        => $value->ReceiveWeight,
	                ]);
	            } else {
	                $s_a_g_info->save(['Weight' => $s_a_g_info->Weight + $value->ReceiveWeight]);
	            }
            }
        }
        
        //入库成功通知
        Sendmessage::Orderreceipt(2, $data['id']);
        return myok('入库成功');
    }

    /**
     * 判断账号是否登录
     * @return boolean [description]
     */
    private function is_login()
    {
        $data = UserModel::is_sessionlogin();
        if (!$data['code']) {
            $data['options'] = 'relogin';
            json($data)->send();
            exit;
        }
    }
}
